import { Button, Card, Form, Image, Input, Select, Space, Table } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import React, { useEffect, useState } from 'react'
import { ColumnsType } from 'antd/lib/table'
import { changeStatus, getDictList, getHospitalList } from '@/api/hospital/hospitList'
import { IDictList, IFormData, IHospitalItem, IHospitalList } from '@/api/hospital/model/hospitalListTypes'
import { useNavigate } from 'react-router-dom'
const { Option } = Select
export default function HospitalList() {
    const navigate = useNavigate()
    /**
     * 查询
     */
    const onFinish = () => {
        // 1. 获取表单数据的值
        // 2. 设置fields状态
        // 3. current设置成 第一页
        let fields = form.getFieldsValue()
        setFields(fields)
        setCurrent(1)
    }
    const reset = () => {
        form.setFieldsValue({
            hoscode: undefined,
            hosname: undefined,
            hostype: undefined,
            provinceCode: undefined,
            cityCode: undefined,
            districtCode: undefined,
            status: undefined
        })
        setFields({})
        setCurrent(1)
    }
    const columns: ColumnsType<any> = [
        {
            title: '序号',
            width: 60,
            align: 'center',
            render: (value: any, rows: any, index: number) => {
                return (current - 1) * pageSize + (index + 1)
            }
        },
        {
            title: '医院logo',
            width: 100,
            render(rows: IHospitalItem) {
                return <Image src={'data:image/jepg;base64,' + rows.logoData} width={100} />
            }
        },
        {
            title: '医院名称',
            dataIndex: 'hosname'
        },
        {
            title: '等级',
            render(rows: IHospitalItem) {
                return rows.param.hostypeString
            }
        },
        {
            title: '详细地址',
            render(rows: IHospitalItem) {
                return rows.param.fullAddress
            }
        },
        {
            title: '状态',
            render(rows: IHospitalItem) {
                return rows.status ? '上线' : '下线'
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime'
        },
        {
            title: '操作',
            render(rows: IHospitalItem) {
                return (
                    <Space>
                        <Button type='primary' onClick={()=>navigate('/syt/hospital/hospitalList/show/' + rows.id)}>查看</Button>
                        <Button type='primary' onClick={()=>navigate('/syt/hospital/hospitalList/schedule/' + rows.hoscode)}>排班</Button>
                        <Button type='primary' onClick={()=>_changeStatus(rows.id, rows.status)}>{rows.status ? '下线' : '上线'}</Button>
                    </Space>
                )
            }
        }
    ]
    const [form] = Form.useForm()
    // 定义状态
    let [loading, setLoading] = useState<boolean>(false)
    let [province, setProvince] = useState<IDictList>([])
    let [cities, setCities] = useState<IDictList>([])
    let [district, setDistrict] = useState<IDictList>([])

    // 医院列表相关状态
    let [current, setCurrent] = useState<number>(1)
    let [pageSize, setPageSize] = useState<number>(5)
    let [total, setTotal] = useState<number>(1)
    let [hospitalList, setHospitalList] = useState<IHospitalList>([])
    let [hosTypes, setHosTypes] = useState<IDictList>([])

    let [fields, setFields] = useState<IFormData>({})

    const _changeStatus = async (id:string, status:number)=>{
        status = status ? 0 : 1
        // 1. 发送ajax请求改变 状态
        await changeStatus(id, status)
        // 2. 更新医院列表
        _getHospitalList()
    }

    /**
     * 获取省列表数据
     */
    const getProvince = async () => {
        setLoading(true)
        let province = await getDictList(86)
        setProvince(province)
        setLoading(false)
    }
    /**
     * 根据省id获取市列表并设置状态
     * @param id 
     */
    const getCities = async (id: number | string) => {
        // 重置市 和 区  (1) 重置状态数据， （2）重置表单的值
        form.setFieldsValue({
            cityCode: undefined,
            districtCode: undefined
        })
        setDistrict([])
        // 获取新的市的数据
        setLoading(true)
        let cities = await getDictList(id)
        setCities(cities)
        setLoading(false)
    }
    /**
     * 根据市id获取区列表数据
     * @param id 
     */
    const getDistrict = async (id: number | string) => {
        // 重置区的表单数据
        form.setFieldsValue({
            districtCode: undefined
        })
        // 获取新的区数据并设置状态
        setLoading(true)
        let district = await getDictList(id)
        setDistrict(district)
        setLoading(false)
    }
    /**
     * 获取医院列表分页数据
     */
    const _getHospitalList = async () => {
        let { content, totalElements } = await getHospitalList({ page: current, limit: pageSize, ...fields })
        console.log('content: ', content)
        console.log('total: ', totalElements)
        // 设置医院列表状态数据和总条数
        setHospitalList(content)
        setTotal(totalElements)
    }

    const _getHospitalTypes = async () => {
        let hosTypes = await getDictList(10000)
        setHosTypes(hosTypes)
    }
    useEffect(() => {
        getProvince()
        _getHospitalTypes()
    }, [])

    useEffect(() => {
        _getHospitalList()
        console.log('123123')
    }, [current, pageSize, fields.cityCode, fields.districtCode, fields.hoscode, fields.hosname, fields.hostype, fields.provinceCode, fields.status])

    return (
        <Card>
            <Form
                layout='inline'
                name="basic"
                onFinish={onFinish}
                form={form}
            >
                <Form.Item name="provinceCode" >
                    <Select
                        loading={loading}
                        className="mb20"
                        style={{ width: 200 }}
                        placeholder="请选择省"
                        /**
                         * 当改变下拉框选择时，会触发onChange，并且将Option中的value属性值，传递过来作为参数
                         */
                        onChange={(id: string | number) => {
                            // 调用获取市列表方法
                            getCities(id)
                        }}
                    >
                        {province.map(item => {
                            return (<Option key={item.id} value={item.value}>{item.name}</Option>)
                        })}
                    </Select>
                </Form.Item>
                <Form.Item name="cityCode">
                    <Select
                        loading={loading}
                        style={{ width: 200 }}
                        placeholder="请选择市"
                        onChange={(id: string | number) => {
                            getDistrict(id)
                        }}
                    >
                        {cities.map(city => (
                            <Option key={city.id} value={city.value}>{city.name}</Option>
                        ))}

                    </Select>
                </Form.Item>
                <Form.Item name="districtCode">
                    <Select
                        loading={loading}
                        style={{ width: 200 }}
                        placeholder="请选择区"
                        onChange={() => { }}
                    >
                        {district.map(item => (
                            <Option value={item.value} key={item.id}>{item.name}</Option>
                        ))}

                    </Select>
                </Form.Item>
                <Form.Item
                    name="hosname"
                >
                    <Input placeholder='医院名称' />
                </Form.Item>
                <Form.Item
                    name="hoscode"
                >
                    <Input placeholder='医院编号' />
                </Form.Item>

                <Form.Item name="hostype">
                    <Select
                        style={{ width: 200 }}
                        placeholder="医院类型"
                        onChange={() => { }}
                    >
                        {hosTypes.map(type => (
                            <Option value={type.value} key={type.id}>{type.name}</Option>
                        ))}

                    </Select>
                </Form.Item>
                <Form.Item name="status">
                    <Select
                        style={{ width: 200 }}
                        placeholder="医院状态"
                        onChange={() => { }}
                    >
                        <Option value={1}>上线</Option>
                        <Option value={0}>下线</Option>
                        
                    </Select>
                </Form.Item>

                <Form.Item>
                    <Space>
                        <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                            查询
                        </Button>
                        <Button onClick={reset} disabled={!fields.cityCode && !fields.districtCode && !fields.hoscode && !fields.hosname && !fields.hostype && !fields.provinceCode && !fields.status}>清空</Button>
                    </Space>
                </Form.Item>
            </Form>

            <Table
                loading={loading}
                rowKey={'id'}
                className="mt20"
                columns={columns}
                dataSource={hospitalList}
                pagination={{
                    current,
                    pageSize,
                    total,
                    onChange: (page: number, pageSize: number) => {
                        setCurrent(page)
                        setPageSize(pageSize)
                    },
                    showQuickJumper: true,
                    showSizeChanger: true,
                    pageSizeOptions: [10, 20, 30]
                }}
            />
        </Card>
    )
}
